package com.ruoyi.logistics.service.impl;

import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.annotation.AfterEsTrigger;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.easyExcelHandler.listener.logisticsTracking.QcLogisticsTrackingListener;
import com.ruoyi.logistics.domain.DTO.QcLogisticsTrackingEsDTO;
import com.ruoyi.logistics.domain.DTO.QueryCondition;
import com.ruoyi.logistics.domain.DTO.QueryItem;
import com.ruoyi.logistics.domain.Vo.QcLogisticsTrackingVo;
import com.ruoyi.logistics.service.IQcLogisticsTrackingEsService;
import com.ruoyi.logistics.service.IQclogisticsTrackingRepository;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.SearchScrollHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import com.ruoyi.logistics.mapper.QcLogisticsTrackingMapper;
import com.ruoyi.logistics.domain.QcLogisticsTracking;
import com.ruoyi.logistics.service.IQcLogisticsTrackingService;

import javax.annotation.Resource;

/**
 * 物流追踪Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-24
 */
@Service
public class QcLogisticsTrackingServiceImpl implements IQcLogisticsTrackingService {
    @Autowired
    private QcLogisticsTrackingMapper qcLogisticsTrackingMapper;

    @Resource(name = "threadPoolTaskExecutor")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Autowired
    private IQcLogisticsTrackingEsService qcLogisticsTrackingEsService;

    @Autowired
    private IQclogisticsTrackingRepository qclogisticsTrackingRepository;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchTemplate;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 查询物流追踪
     *
     * @param id 物流追踪主键
     * @return 物流追踪
     */
    @Override
    public QcLogisticsTracking selectQcLogisticsTrackingById(Long id) {
        QcLogisticsTracking qcLogisticsTracking = qcLogisticsTrackingMapper.selectQcLogisticsTrackingById(id);
        QcLogisticsTrackingEsDTO qcLogisticsTrackingEsDTO = new QcLogisticsTrackingEsDTO();
        BeanUtils.copyProperties(qcLogisticsTracking, qcLogisticsTrackingEsDTO);
        qcLogisticsTrackingEsService.saveQcLogisticsTracking(qcLogisticsTrackingEsDTO);
        // this.selectQcLogisticsTrackingEsList(new QcLogisticsTracking());
        return qcLogisticsTracking;
    }

    /**
     * 查询物流追踪列表
     *
     * @param qcLogisticsTracking 物流追踪
     * @return 物流追踪
     */
    @Override
    public List<QcLogisticsTracking> selectQcLogisticsTrackingList(QcLogisticsTracking qcLogisticsTracking) {
        return qcLogisticsTrackingMapper.selectQcLogisticsTrackingList(qcLogisticsTracking);
    }

    /**
     * ES数据查询
     *
     * @param qcLogisticsTracking
     * @return
     */
    @Override
    public SearchHits<QcLogisticsTrackingEsDTO> selectQcLogisticsTrackingEsList(QcLogisticsTrackingVo qcLogisticsTracking) {

        // this.scrollToPage(qcLogisticsTracking.getPageNum(), qcLogisticsTracking.getPageSize(), qcLogisticsTracking);
        ObjectMapper objectMapper = new ObjectMapper();
        // String queryJson = "[{\"condition\":\"or\",\"list\":[{\"oper\":\"gt\",\"field\":\"sendDate\",\"value\":\"2025-07-18 00:00:00\",\"condition\":\"and\",\"dataType\":\"date\"},{\"oper\":\"lt\",\"field\":\"sendDate\",\"value\":\"2025-07-21 23:59:59\",\"condition\":\"and\"\"dataType\":\"date\"},{\"oper\":\"eq\",\"field\":\"shipmentId\",\"value\":\"FBA5DDSFDEE2569\",\"condition\":\"and\"\"dataType\":\"String\"}]}]";
        // List<QueryCondition> conditions = new ArrayList<>();
        // List<QueryCondition> conditions = JSON.parseArray(queryJson, QueryCondition.class);
        // try {
        //     // 解析JSON查询条件
        //     List<QueryCondition> jsonObject = JSON.parseArray(queryJson, QueryCondition.class);
        //     List<QueryCondition> tt = jsonObject;
        //     // jsonObject.forEach(e -> {
        //     //     JSONObject obj = JSONObject.parseObject(e.toString());
        //     //     QueryCondition queryCondition = new QueryCondition();
        //     //     queryCondition.setCondition(obj.get("condition").toString());
        //     //     queryCondition.setList(JSON.parseArray(obj.get("list").toString(), QueryItem.class));
        //     //     conditions.add(queryCondition);
        //     // });
        //
        //     // conditions = objectMapper.readValue(
        //     //         queryJson,
        //     //         new TypeReference<List<QueryCondition>>() {
        //     //         }
        //     // );
        // } catch (Exception e) {
        //
        // }
        // // 创建Bool查询构建器
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        // 添加shipment_id精确匹配条件
        // boolQuery.should(QueryBuilders.termQuery("shipmentId", "FBA5DDSFDEE2569"));

        // 创建send_date范围查询
        // RangeQueryBuilder dateRangeQuery = QueryBuilders.rangeQuery("sendDate")
        //         .gt("2025-07-18 00:00:00")  // 大于2025-07-18 00:00:00
        //         .lt("2025-07-21 23:59:59") // 小于2025-07-21 23:59:59
        //         .format("yyyy-MM-dd HH:mm:ss");  // 指定日期格式

        // RangeQueryBuilder dateRangeQuery2 = QueryBuilders.rangeQuery("sendDate")
        //         // .gt("2025-07-18 00:00:00")  // 大于2025-07-18 00:00:00
        //         .lt("2025-07-21 23:59:59") // 小于2025-07-21 23:59:59
        //         .format("yyyy-MM-dd HH:mm:ss");  // 指定日期格式

        // 添加日期范围条件
        // boolQuery.should(dateRangeQuery);
        // BoolQueryBuilder ttf = boolQuery;
        SearchRequest searchRequest = new SearchRequest("qc_logistics_tracking");
        // 构建查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        if (qcLogisticsTracking.getQueryParam().size() > 0) {
            SearchSourceBuilder searchSourceBuilderQuery = DynamicQueryBuilder.buildQuery(qcLogisticsTracking.getQueryParam());
            searchSourceBuilder.query(searchSourceBuilderQuery.query());
        }
        if (qcLogisticsTracking.getShipmentId() != null && qcLogisticsTracking.getShipmentId() != "") {
            String shipmentId = qcLogisticsTracking.getShipmentId();
            String[] shipmentIdArr = shipmentId.split("\\s+");
            if (shipmentIdArr.length > 1) {
                ArrayList<String> shipmentIdList = new ArrayList<>(Arrays.asList(shipmentIdArr));
                qcLogisticsTracking.setShipmentIdList(shipmentIdList);
                qcLogisticsTracking.setShipmentId(null);
            }
        }
        // 判断当前货架号是否存在
        if (StringUtils.isNotBlank(qcLogisticsTracking.getShipmentId())) {
            // like查詢
            boolQuery.must(QueryBuilders.wildcardQuery("shipmentId", "*" + qcLogisticsTracking.getShipmentId() + "*"));
        }
        if (qcLogisticsTracking.getShipmentIdList().size() > 0) {
            // in查詢
            boolQuery.must(QueryBuilders.termsQuery("shipmentId", qcLogisticsTracking.getShipmentIdList()));
        }
        if (qcLogisticsTracking.getAccount() != null && qcLogisticsTracking.getAccount() != "") {
            String account = qcLogisticsTracking.getAccount();
            String[] accountArr = account.split("\\s+");
            if (accountArr.length > 1) {
                ArrayList<String> accountList = new ArrayList<>(Arrays.asList(accountArr));
                qcLogisticsTracking.setAccountList(accountList);
                qcLogisticsTracking.setAccount(null);
            }
        }
        if (StringUtils.isNotBlank(qcLogisticsTracking.getAccount())) {
            // like查詢
            boolQuery.must(QueryBuilders.wildcardQuery("account", "*" + qcLogisticsTracking.getAccount() + "*"));
        }
        if (qcLogisticsTracking.getAccountList().size() > 0) {
            // in查詢
            boolQuery.must(QueryBuilders.termsQuery("account", qcLogisticsTracking.getAccountList()));
        }
        searchSourceBuilder.query(boolQuery);

        // searchSourceBuilder.addRescorer(searchSourceBuilder1)
        // SearchSourceBuilder ddff = searchSourceBuilder;
        // SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // sourceBuilder.query(QueryBuilders.boolQuery()
        //                 .should(QueryBuilders.matchQuery("shipmentId", "FBA5DDSFDEE2569"))
        //         // .must(QueryBuilders.termQuery("status", "active")) // Example of AND condition
        // );
        // NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
        //         .withQuery(boolQuery)
        //         .withPageable(PageRequest.of(0, 500))
        //         .withTrackTotalHits(Boolean.TRUE)
        //         // .withSort()
        //         .build();
        // 创建排序
        if (StringUtils.isEmpty(qcLogisticsTracking.getFieldName()) || StringUtils.isEmpty(qcLogisticsTracking.getSortName())) {
            qcLogisticsTracking.setFieldName("id");
            qcLogisticsTracking.setSortName("DESC");
        }

        Integer dataNum = qcLogisticsTracking.getPageNum() * qcLogisticsTracking.getPageSize();

        SearchHits<QcLogisticsTrackingEsDTO> search;


        if (dataNum.compareTo(10000) > 0) {
            NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                    .withQuery(searchSourceBuilder.query())
                    // .withPageable(PageRequest.of(qcLogisticsTracking.getPageNum() - 1, qcLogisticsTracking.getPageSize()))
                    .withTrackTotalHits(Boolean.TRUE)
                    // .withSort(SortBuilders.fieldSort(qcLogisticsTracking.getFieldName()).order(qcLogisticsTracking.getSortName().equals("ASC") ? SortOrder.ASC :
                    //         SortOrder.DESC))  // 排序
                    .withSort(SortBuilders.fieldSort("id").order(SortOrder.DESC))  // 排序
                    .withMaxResults(qcLogisticsTracking.getPageSize())
                    .build();
            if (qcLogisticsTracking.getSearchAfterValuesBase64() != null) {
                // String SearchAfterValuesBase64 = new String(Base64.getDecoder().decode(qcLogisticsTracking.getSearchAfterValuesBase64()));
                JSONArray tt = JSON.parseArray(qcLogisticsTracking.getSearchAfterValuesBase64());
                searchQuery.setSearchAfter(JSON.parseArray(qcLogisticsTracking.getSearchAfterValuesBase64()));
            }
            QueryBuilder query = searchQuery.getQuery();
            QueryBuilder zf = query;
            search = elasticsearchTemplate.search(searchQuery, QcLogisticsTrackingEsDTO.class);

        } else {

            NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                    .withQuery(searchSourceBuilder.query())
                    .withPageable(PageRequest.of(qcLogisticsTracking.getPageNum() - 1, qcLogisticsTracking.getPageSize()))
                    .withTrackTotalHits(Boolean.TRUE)
                    // .withSort(SortBuilders.fieldSort(qcLogisticsTracking.getFieldName()).order(qcLogisticsTracking.getSortName().equals("ASC") ? SortOrder.ASC :
                    //         SortOrder.DESC))  // 排序
                    .withSort(SortBuilders.fieldSort("id").order(SortOrder.DESC))  // 排序
                    .build();
            QueryBuilder query = searchQuery.getQuery();
            QueryBuilder zf = query;
            search = elasticsearchTemplate.search(searchQuery, QcLogisticsTrackingEsDTO.class);

        }
        SearchHits<QcLogisticsTrackingEsDTO> tft = search;

        return search;
    }

    /**
     * 获取指定页数对应排序
     *
     * @param qcLogisticsTracking
     * @return
     */
    @Override
    public String getScrollToPage(QcLogisticsTrackingVo qcLogisticsTracking) {
        String s = this.scrollToPage(qcLogisticsTracking.getPageNum(), qcLogisticsTracking.getPageSize(), qcLogisticsTracking);

        return s;
    }

    /**
     * 获取滚动页
     *
     * @param targetPage
     * @param pageSize
     * @param qcLogisticsTracking
     * @return
     */
    public String scrollToPage(int targetPage, int pageSize, QcLogisticsTrackingVo qcLogisticsTracking) {
        // 计算需要跳过的页数
        int pagesToSkip = targetPage;

        // 初始化滚动查询
        NativeSearchQuery initialQuery = new NativeSearchQueryBuilder()
                .withPageable(PageRequest.of(0, pageSize))
                .withSort(SortBuilders.fieldSort("id").order(SortOrder.DESC))  // 排序
                .build();

        SearchScrollHits<QcLogisticsTrackingEsDTO> scroll = elasticsearchTemplate.searchScrollStart(60000, initialQuery, QcLogisticsTrackingEsDTO.class, IndexCoordinates.of("qc_logistics_tracking"));
        String scrollId = scroll.getScrollId();

        try {
            // 跳过前面的页数
            for (int i = 0; i < pagesToSkip; i++) {
                scroll = elasticsearchTemplate.searchScrollContinue(scrollId, 60000, QcLogisticsTrackingEsDTO.class, IndexCoordinates.of("qc_logistics_tracking"));
                scrollId = scroll.getScrollId();

                if (scroll.getSearchHits().isEmpty()) {
                    throw new RuntimeException("没有足够数据获取，请确认后重试");
                }
            }
            List<SearchHit<QcLogisticsTrackingEsDTO>> dataList = StreamSupport.stream(scroll.spliterator(), false)
                    .collect(Collectors.toList());
            List<Object> sortValues = dataList.get(dataList.size() - 1).getSortValues();
            String searchAfterValuesBase64 = JSON.toJSONString(sortValues);
            String tt = searchAfterValuesBase64;
            return searchAfterValuesBase64;
        } finally {
            List<String> scrollIds = new ArrayList<>();
            scrollIds.add(scrollId);
            // 清除滚动上下文
            elasticsearchTemplate.searchScrollClear(scrollIds);
        }
    }

    // public List<SearchHit<QcLogisticsTrackingEsDTO>> scrollToPage(int targetPage, int pageSize, QcLogisticsTrackingVo qcLogisticsTracking) {
    //     // 计算需要跳过的页数
    //     int pagesToSkip = targetPage;
    //
    //     // 初始化滚动查询
    //     NativeSearchQuery initialQuery = new NativeSearchQueryBuilder()
    //             .withPageable(PageRequest.of(0, pageSize))
    //             .withSort(SortBuilders.fieldSort("id").order(SortOrder.DESC))  // 排序
    //             .build();
    //
    //     SearchScrollHits<QcLogisticsTrackingEsDTO> scroll = elasticsearchTemplate.searchScrollStart(60000, initialQuery, QcLogisticsTrackingEsDTO.class, IndexCoordinates.of("qc_logistics_tracking"));
    //     String scrollId = scroll.getScrollId();
    //
    //     try {
    //         // 跳过前面的页数
    //         for (int i = 0; i < pagesToSkip-1; i++) {
    //             scroll = elasticsearchTemplate.searchScrollContinue(scrollId, 60000, QcLogisticsTrackingEsDTO.class, IndexCoordinates.of("qc_logistics_tracking"));
    //             scrollId = scroll.getScrollId();
    //
    //             if (scroll.getSearchHits().isEmpty()) {
    //                 return Collections.emptyList(); // 没有足够的数据到达目标页
    //             }
    //         }
    //         List<SearchHit<QcLogisticsTrackingEsDTO>> dd = StreamSupport.stream(scroll.spliterator(), false)
    //                 .collect(Collectors.toList());
    //         List<SearchHit<QcLogisticsTrackingEsDTO>> ddf = dd;
    //         // 返回目标页的数据
    //         return StreamSupport.stream(scroll.spliterator(), false)
    //                 .collect(Collectors.toList());
    //     } finally {
    //         // 清除滚动上下文
    //         // elasticsearchTemplate.searchScrollClear(scrollId);
    //     }
    // }

    // /**
    //  * ES数据查询
    //  *
    //  * @param qcLogisticsTracking
    //  * @return
    //  */
    // @Override
    // public SearchHits<QcLogisticsTrackingEsDTO> selectQcLogisticsTrackingEsList(QcLogisticsTrackingVo qcLogisticsTracking) {
    //     ObjectMapper objectMapper = new ObjectMapper();
    //     // String queryJson = "[{\"condition\":\"or\",\"list\":[{\"oper\":\"gt\",\"field\":\"sendDate\",\"value\":\"2025-07-18 00:00:00\",\"condition\":\"and\",\"dataType\":\"date\"},{\"oper\":\"lt\",\"field\":\"sendDate\",\"value\":\"2025-07-21 23:59:59\",\"condition\":\"and\"\"dataType\":\"date\"},{\"oper\":\"eq\",\"field\":\"shipmentId\",\"value\":\"FBA5DDSFDEE2569\",\"condition\":\"and\"\"dataType\":\"String\"}]}]";
    //     // List<QueryCondition> conditions = new ArrayList<>();
    //     // List<QueryCondition> conditions = JSON.parseArray(queryJson, QueryCondition.class);
    //     // try {
    //     //     // 解析JSON查询条件
    //     //     List<QueryCondition> jsonObject = JSON.parseArray(queryJson, QueryCondition.class);
    //     //     List<QueryCondition> tt = jsonObject;
    //     //     // jsonObject.forEach(e -> {
    //     //     //     JSONObject obj = JSONObject.parseObject(e.toString());
    //     //     //     QueryCondition queryCondition = new QueryCondition();
    //     //     //     queryCondition.setCondition(obj.get("condition").toString());
    //     //     //     queryCondition.setList(JSON.parseArray(obj.get("list").toString(), QueryItem.class));
    //     //     //     conditions.add(queryCondition);
    //     //     // });
    //     //
    //     //     // conditions = objectMapper.readValue(
    //     //     //         queryJson,
    //     //     //         new TypeReference<List<QueryCondition>>() {
    //     //     //         }
    //     //     // );
    //     // } catch (Exception e) {
    //     //
    //     // }
    //     // // 创建Bool查询构建器
    //     BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
    //
    //     // 添加shipment_id精确匹配条件
    //     // boolQuery.should(QueryBuilders.termQuery("shipmentId", "FBA5DDSFDEE2569"));
    //
    //     // 创建send_date范围查询
    //     // RangeQueryBuilder dateRangeQuery = QueryBuilders.rangeQuery("sendDate")
    //     //         .gt("2025-07-18 00:00:00")  // 大于2025-07-18 00:00:00
    //     //         .lt("2025-07-21 23:59:59") // 小于2025-07-21 23:59:59
    //     //         .format("yyyy-MM-dd HH:mm:ss");  // 指定日期格式
    //
    //     // RangeQueryBuilder dateRangeQuery2 = QueryBuilders.rangeQuery("sendDate")
    //     //         // .gt("2025-07-18 00:00:00")  // 大于2025-07-18 00:00:00
    //     //         .lt("2025-07-21 23:59:59") // 小于2025-07-21 23:59:59
    //     //         .format("yyyy-MM-dd HH:mm:ss");  // 指定日期格式
    //
    //     // 添加日期范围条件
    //     // boolQuery.should(dateRangeQuery);
    //     // BoolQueryBuilder ttf = boolQuery;
    //     // 构建查询
    //     SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    //     if (qcLogisticsTracking.getQueryParam().size() > 0) {
    //         SearchSourceBuilder searchSourceBuilderQuery = DynamicQueryBuilder.buildQuery(qcLogisticsTracking.getQueryParam());
    //         searchSourceBuilder.query(searchSourceBuilderQuery.query());
    //     }
    //     if (qcLogisticsTracking.getShipmentId() != null && qcLogisticsTracking.getShipmentId() != "") {
    //         String shipmentId = qcLogisticsTracking.getShipmentId();
    //         String[] shipmentIdArr = shipmentId.split("\\s+");
    //         if (shipmentIdArr.length > 1) {
    //             ArrayList<String> shipmentIdList = new ArrayList<>(Arrays.asList(shipmentIdArr));
    //             qcLogisticsTracking.setShipmentIdList(shipmentIdList);
    //             qcLogisticsTracking.setShipmentId(null);
    //         }
    //     }
    //     // 判断当前货架号是否存在
    //     if (StringUtils.isNotBlank(qcLogisticsTracking.getShipmentId())) {
    //         // like查詢
    //         boolQuery.must(QueryBuilders.wildcardQuery("shipmentId", "*" + qcLogisticsTracking.getShipmentId() + "*"));
    //     }
    //     if (qcLogisticsTracking.getShipmentIdList().size() > 0) {
    //         // in查詢
    //         boolQuery.must(QueryBuilders.termsQuery("shipmentId", qcLogisticsTracking.getShipmentIdList()));
    //     }
    //     if (qcLogisticsTracking.getAccount() != null && qcLogisticsTracking.getAccount() != "") {
    //         String account = qcLogisticsTracking.getAccount();
    //         String[] accountArr = account.split("\\s+");
    //         if (accountArr.length > 1) {
    //             ArrayList<String> accountList = new ArrayList<>(Arrays.asList(accountArr));
    //             qcLogisticsTracking.setAccountList(accountList);
    //             qcLogisticsTracking.setAccount(null);
    //         }
    //     }
    //     if (StringUtils.isNotBlank(qcLogisticsTracking.getAccount())) {
    //         // like查詢
    //         boolQuery.must(QueryBuilders.wildcardQuery("account", "*" + qcLogisticsTracking.getAccount() + "*"));
    //     }
    //     if (qcLogisticsTracking.getAccountList().size() > 0) {
    //         // in查詢
    //         boolQuery.must(QueryBuilders.termsQuery("account", qcLogisticsTracking.getAccountList()));
    //     }
    //     searchSourceBuilder.query(boolQuery);
    //
    //     // searchSourceBuilder.addRescorer(searchSourceBuilder1)
    //     // SearchSourceBuilder ddff = searchSourceBuilder;
    //     // SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
    //     // sourceBuilder.query(QueryBuilders.boolQuery()
    //     //                 .should(QueryBuilders.matchQuery("shipmentId", "FBA5DDSFDEE2569"))
    //     //         // .must(QueryBuilders.termQuery("status", "active")) // Example of AND condition
    //     // );
    //     // NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
    //     //         .withQuery(boolQuery)
    //     //         .withPageable(PageRequest.of(0, 500))
    //     //         .withTrackTotalHits(Boolean.TRUE)
    //     //         // .withSort()
    //     //         .build();
    //     NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
    //             .withQuery(searchSourceBuilder.query())
    //             .withPageable(PageRequest.of(qcLogisticsTracking.getPageNum() - 1, qcLogisticsTracking.getPageSize()))
    //             .withTrackTotalHits(Boolean.TRUE)
    //             // .withSort()
    //             .build();
    //     QueryBuilder query = searchQuery.getQuery();
    //     QueryBuilder zf = query;
    //     SearchHits<QcLogisticsTrackingEsDTO> search = elasticsearchTemplate.search(searchQuery, QcLogisticsTrackingEsDTO.class);
    //     SearchHits<QcLogisticsTrackingEsDTO> tt = search;
    //     // Pageable paging = PageRequest.of(qcLogisticsTracking.getPageNum(), qcLogisticsTracking.getPageSize());
    //     // Iterable<QcLogisticsTrackingEsDTO> all = qclogisticsTrackingRepository.findAll(paging);
    //     // Iterable<QcLogisticsTrackingEsDTO> dd = all;
    //
    //     return search;
    // }

    // /**
    //  * ES数据查询
    //  *
    //  * @param qcLogisticsTracking
    //  * @return
    //  */
    // @Override
    // public List<QcLogisticsTrackingEsDTO> selectQcLogisticsTrackingEsList(QcLogisticsTrackingVo qcLogisticsTracking) {
    //     ObjectMapper objectMapper = new ObjectMapper();
    //     String queryJson = "[{\"condition\":\"or\",\"list\":[{\"oper\":\"gt\",\"field\":\"sendDate\",\"value\":\"2025-07-18 00:00:00\",\"condition\":\"and\",\"dataType\":\"date\"},{\"oper\":\"lt\",\"field\":\"sendDate\",\"value\":\"2025-07-21 23:59:59\",\"condition\":\"and\"\"dataType\":\"date\"},{\"oper\":\"eq\",\"field\":\"shipmentId\",\"value\":\"FBA5DDSFDEE2569\",\"condition\":\"and\"\"dataType\":\"String\"}]}]";
    //     List<QueryCondition> conditions = new ArrayList<>();
    //     try {
    //         // 解析JSON查询条件
    //         JSONArray jsonObject = JSON.parseArray(queryJson);
    //         jsonObject.forEach(e -> {
    //             JSONObject obj = JSONObject.parseObject(e.toString());
    //             QueryCondition queryCondition = new QueryCondition();
    //             queryCondition.setCondition(obj.get("condition").toString());
    //             queryCondition.setList(JSON.parseArray(obj.get("list").toString(), QueryItem.class));
    //             conditions.add(queryCondition);
    //         });
    //
    //         // conditions = objectMapper.readValue(
    //         //         queryJson,
    //         //         new TypeReference<List<QueryCondition>>() {
    //         //         }
    //         // );
    //     } catch (Exception e) {
    //
    //     }
    //     List<QueryCondition> qf = conditions;
    //     // // 创建Bool查询构建器
    //     BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
    //
    //     // 添加shipment_id精确匹配条件
    //     // boolQuery.should(QueryBuilders.termQuery("shipmentId", "FBA5DDSFDEE2569"));
    //
    //     // 创建send_date范围查询
    //     // RangeQueryBuilder dateRangeQuery = QueryBuilders.rangeQuery("sendDate")
    //     //         .gt("2025-07-18 00:00:00")  // 大于2025-07-18 00:00:00
    //     //         .lt("2025-07-21 23:59:59") // 小于2025-07-21 23:59:59
    //     //         .format("yyyy-MM-dd HH:mm:ss");  // 指定日期格式
    //
    //     // RangeQueryBuilder dateRangeQuery2 = QueryBuilders.rangeQuery("sendDate")
    //     //         // .gt("2025-07-18 00:00:00")  // 大于2025-07-18 00:00:00
    //     //         .lt("2025-07-21 23:59:59") // 小于2025-07-21 23:59:59
    //     //         .format("yyyy-MM-dd HH:mm:ss");  // 指定日期格式
    //
    //     // 添加日期范围条件
    //     // boolQuery.should(dateRangeQuery);
    //     // BoolQueryBuilder ttf = boolQuery;
    //     // 构建查询
    //     SearchSourceBuilder searchSourceBuilder = DynamicQueryBuilder.buildQuery(conditions);
    //     // SearchSourceBuilder ddff = searchSourceBuilder;
    //     // SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
    //     // sourceBuilder.query(QueryBuilders.boolQuery()
    //     //                 .should(QueryBuilders.matchQuery("shipmentId", "FBA5DDSFDEE2569"))
    //     //         // .must(QueryBuilders.termQuery("status", "active")) // Example of AND condition
    //     // );
    //     // NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
    //     //         .withQuery(boolQuery)
    //     //         .withPageable(PageRequest.of(0, 500))
    //     //         .withTrackTotalHits(Boolean.TRUE)
    //     //         // .withSort()
    //     //         .build();
    //     NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
    //             .withQuery(searchSourceBuilder.query())
    //             .withPageable(PageRequest.of(0, 500))
    //             .withTrackTotalHits(Boolean.TRUE)
    //             // .withSort()
    //             .build();
    //     QueryBuilder query = searchQuery.getQuery();
    //     QueryBuilder zf = query;
    //     SearchHits<QcLogisticsTrackingEsDTO> search = elasticsearchTemplate.search(searchQuery, QcLogisticsTrackingEsDTO.class);
    //     SearchHits<QcLogisticsTrackingEsDTO> tt = search;
    //     Pageable paging = PageRequest.of(1, 500);
    //     Iterable<QcLogisticsTrackingEsDTO> all = qclogisticsTrackingRepository.findAll(paging);
    //     Iterable<QcLogisticsTrackingEsDTO> dd = all;
    //
    //     return new ArrayList<>();
    // }

    /**
     * 新增物流追踪
     *
     * @param qcLogisticsTracking 物流追踪
     * @return 结果
     */
    @Override
    public int insertQcLogisticsTracking(QcLogisticsTracking qcLogisticsTracking) {
        qcLogisticsTracking.setCreateTime(DateUtils.getNowDate());
        return qcLogisticsTrackingMapper.insertQcLogisticsTracking(qcLogisticsTracking);
    }

    /**
     * 修改物流追踪
     *
     * @param qcLogisticsTracking 物流追踪
     * @return 结果
     */
    @AfterEsTrigger("syncEsQcLogisticsTracking")
    @Override
    public int updateQcLogisticsTracking(QcLogisticsTracking qcLogisticsTracking) {
        qcLogisticsTracking.setUpdateTime(DateUtils.getNowDate());
        qcLogisticsTracking.setIsEs(2);
        System.out.println("我是更新方法");
        return qcLogisticsTrackingMapper.updateQcLogisticsTracking(qcLogisticsTracking);
    }

    // public void processEsRelated() {
    //
    //     System.out.println("我是调用方法");
    // }

    /**
     * 批量删除物流追踪
     *
     * @param ids 需要删除的物流追踪主键
     * @return 结果
     */
    @Override
    public int deleteQcLogisticsTrackingByIds(Long[] ids) {
        return qcLogisticsTrackingMapper.deleteQcLogisticsTrackingByIds(ids);
    }

    /**
     * 删除物流追踪信息
     *
     * @param id 物流追踪主键
     * @return 结果
     */
    @Override
    public int deleteQcLogisticsTrackingById(Long id) {
        return qcLogisticsTrackingMapper.deleteQcLogisticsTrackingById(id);
    }

    /**
     * 数据导入
     *
     * @param inputStream
     * @param qcLogisticsTrackingService
     */
    @Override
    public void importQcLogisticsTracking(InputStream inputStream, IQcLogisticsTrackingService qcLogisticsTrackingService) {

        QcLogisticsTrackingListener qcLogisticsTrackingListener = new QcLogisticsTrackingListener(qcLogisticsTrackingService);
        EasyExcel.read(inputStream, QcLogisticsTracking.class, qcLogisticsTrackingListener).sheet().doRead();
        List<QcLogisticsTracking> cachedDataList = qcLogisticsTrackingListener.getCachedDataList();
        List<QcLogisticsTracking> tt = cachedDataList;
    }

    /**
     * 将数据导入数据库中
     *
     * @param list
     */
    @Override
    public void importSetQcLogisticsTracking(List<QcLogisticsTracking> list) {
        // qcLogisticsTrackingMapper.batchInsertQcLogisticsTracking(list);
        for (int i = 0; i < 10000; i++) {
            threadPoolTaskExecutor.execute(() -> {
                qcLogisticsTrackingMapper.batchInsertQcLogisticsTracking(list);
            });
        }
    }

    /**
     * 同步ES
     */
    @Override
    public void syncEsQcLogisticsTracking() {
        PageUtils.startPage(1, 1000);
        QcLogisticsTracking qcLogisticsTracking = new QcLogisticsTracking();
        qcLogisticsTracking.setIsEs(2);
        List<QcLogisticsTracking> qcLogisticsTrackings = qcLogisticsTrackingMapper.selectQcLogisticsTrackingList(qcLogisticsTracking);
        if (qcLogisticsTrackings.size() == 0) {
            return;
        }
        List<Long> ids = qcLogisticsTrackings.stream().map(QcLogisticsTracking::getId).collect(Collectors.toList());
        qcLogisticsTrackingMapper.updateQcLogisticsTrackingEsStatus(ids, 1);

        List<QcLogisticsTrackingEsDTO> qcLogisticsTrackingEsDTOS = JSONArray.parseArray(JSON.toJSONString(qcLogisticsTrackings), QcLogisticsTrackingEsDTO.class);
        qcLogisticsTrackingEsService.saveQcLogisticsTrackingList(qcLogisticsTrackingEsDTOS);
    }
}
